# coding:utf-8

import os
import re
import json
import base64
import urllib
import logging
from datetime import date, timedelta
from io import BytesIO

from PIL import Image
from flask import request, redirect, jsonify, current_app, abort
from flask_restful import Api, Resource
from sqlalchemy import or_, and_

from app.enterprise.constant import EnterpriseLevel
from app.enterprise.models import Enterprise
from common.constant import PARTIC_CACHE_KEY, PARTIC_CACHE_TIMEOUT, TAIWAN_CODE
from common.demand_util import demand_bid_count
from app.api.supplier_schemas import demand_id_in_schema
from app.models import get_timestamp
from app.op.constant import (
    DemandStatus, BusinessToKeys, UserType, AreaType,
    UserLevel, MAX_OFFER, ParticStatus,
    UserVisitDemandChannel, FollowType)
from app.op.models import (
    Demand,
    User,
    DemandFinishImg,
    UserTag,
    Area,
    Partic,
    UserVisitDemand,
    UserMarketingInfoJuly
)
from app.token import AuthToken
from app.extensions import db
from .codes import SUCCESS, PARAMS_ILLEGAL, UNAUTHORIZED
from .constant import TOKEN_TIMEOUT, BtnType, EnterpriseDispatchQueryType
from .demand_schemas import (
    demand_id_schema, demand_finish_img_schema,
    enterprise_dispatch_export_schema,
    enterprise_dispatch_in_schema,
    enterprise_dispatch_out_schema
)
from .supplier_codes import DEMAND_NOT_EXIST, NOT_ENGINEER, NOT_ENTERPRISE_USER
from .utils import generate_demand_list_json, generate_demand_info_json
from .views import Response, AuthResource

api = Api()


@api.resource('/Demand/getDemandList')
class DemandsResource(Resource):
    """
    created by chenhj at 2017/8/15
    查询项目列表
    """
    def post(self):
        """
        created by chenhj at 2017/8/15

        """
        data = request.form or {}

        sort = data.get('sort', 'published_at')
        order = data.get('order', 'asc')
        pagesize = int(data.get('pagesize', 20))
        sort_val = data.get('sort_val', None)

        # city参数: all代表全国, mine代表我关注的地域范围, 除前边2个之外的string代表取某个城市数据, 默认是我关注的地域数据
        # 若city为all, 则不需要筛选area_id即可
        area_ids = None
        city = data.get('city', 'mine')

        token = request.cookies.get('opc_token')
        # 如果是工程商登录, 则参与状态改为该工程商对此项目的参与状态
        user = AuthToken.verify_auth_token(token) if token else None

        if city == 'mine':
            # 我关注的
            if not user:
                resp = jsonify(Response(UNAUTHORIZED))
                resp.delete_cookie('opc_token')
                return resp

            # area_ids = user.pack.area_id if user.pack else list()
            area_ids = [i.id for i in user.attention_areas] if user.pack else list()
        if city not in ('all', 'mine'):
            # 特定城市, 若无, 则取特定省份
            c = Area.get_by_args(name=city, type=AreaType.CITY.value)
            area_ids = [c.id] if c else Area.get_city_ids(city)
        # business参数: all代表全部类型, mine代表我关注的业务, id代表某个特定业务, 默认是我关注的业务
        business = list()
        business_type = data.get('business', 'mine')
        if business_type == 'mine':
            if not user:
                resp = jsonify(Response(UNAUTHORIZED))
                resp.delete_cookie('opc_token')
                return resp

            user_tag = UserTag.get_by_args(user_id=user.id)
            for cate, field in BusinessToKeys.items():
                if getattr(user_tag, field, None):
                    business.append(cate)
        if business_type not in ('all', 'mine'):
            business.append(business_type)
        # demand参数: all代表全部项目, mine代表我参与的项目, ongoing代表进行中的项目, free表示免费项目, 默认是全部项目
        mine_demand = False
        status = [
            DemandStatus.ONGOING.value, DemandStatus.COMPETE_DONE.value, DemandStatus.DONE.value,
            DemandStatus.BID_DONE.value, DemandStatus.SECOND_ONGOING.value,
            DemandStatus.FREE_ONGOING.value
        ]
        demand_type = data.get('demand', 'all')
        if demand_type == 'ongoing':
            status = [
                DemandStatus.ONGOING.value, DemandStatus.BID_DONE.value,
                DemandStatus.SECOND_ONGOING.value, DemandStatus.FREE_ONGOING.value
            ]
        if demand_type == 'mine':
            mine_demand = True
        # 免费项目只返回免费竞价中的项目
        if demand_type == 'free':
            status = [DemandStatus.FREE_ONGOING.value]
        else:
            # 若用户为铜牌用户及以上, 则同时返回优先抢单项目
            if (
                user
                and user.highest_level >= UserLevel.LEVEL_3.value
                and user.bronze_medal_valid
            ):
                status.append(DemandStatus.BRONZE_MEDAL_DISCOUNT.value)

        demand_query = Demand.query.filter(
            Demand.deleted_at == 0,
            Demand.status.in_(status),
        )

        if area_ids:
            demand_query = demand_query.filter(Demand.area_id.in_(area_ids))

        # 由于会出现你没关注某个区域,但是仍然派单给你的情况,所以派单的项目需要在过滤区域后再加上
        if user and user.highest_level > UserLevel.LEVEL_3.value and demand_type != 'free':
            demand_query = demand_query.union(
                Demand.query.filter(
                    Demand.deleted_at == 0,
                    Demand.id.in_(Partic.query.filter(
                        Partic.demand_status.in_([
                            DemandStatus.DISPATCHING.value,
                            DemandStatus.MASTER_DISPATCHING.value
                        ]),
                        Partic.supplier_id == user.id
                    ).with_entities(Partic.demand_id)),
                )
            )
        if business:
            demand_query = demand_query.filter(Demand.cate.in_(business))
        if mine_demand:
            if not user:
                resp = jsonify(Response(UNAUTHORIZED))
                resp.delete_cookie('opc_token')
                return resp

            # 只返回抢单成功的和正在排队的(不返回取消跟进的和排队失败的)
            # 小霞要求取消跟进的也要返回 at 2018-3-30
            demand_query = demand_query.join(
                Partic, Partic.demand_id == Demand.id
            ).filter(
                Partic.supplier_id == user.id,
                or_(
                    Partic.status == ParticStatus.SUCCEED.value,
                    and_(
                        Partic.published_count == Demand.published_count,
                        Partic.status == ParticStatus.WAITING.value,
                        Demand.status.notin_([DemandStatus.COMPETE_DONE.value, DemandStatus.DONE.value])
                    )
                )
            )

        # FIXME by chenhj at 2018/5/11 纯粹技术债务,永远过滤金牌订单(假单)
        demand_query = demand_query.filter(Demand.for_gold.__eq__(False))
        taiwan = Area.get_by_id(TAIWAN_CODE)
        if not user or taiwan not in user.attention_areas:
            demand_query = demand_query.filter(Demand.area_id != TAIWAN_CODE)
        cnt = demand_query.count()

        if sort_val:
            demand_query = demand_query.filter(
                getattr(Demand, sort) < sort_val if order == 'desc' else getattr(Demand, sort) > sort_val
            )

        # 如果是工程商登录, 则参与状态改为该工程商对此项目的参与状态
        resp = generate_demand_list_json(demand_query.order_by(
            getattr(getattr(Demand, sort), order)()
        )[:pagesize], user)
        return Response(SUCCESS, {
            'cnt': cnt,
            'list': resp
        })


@api.resource('/Demand/getInfo')
class DemandInfoResource(Resource):
    """
    created by chenhj at 2017/8/15
    获取需求信息
    """
    def post(self):
        """
        created by chenhj at 2017/8/15

        """
        data, errors = demand_id_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        demand = Demand.get_by_id(data['id'])
        # FIXME by chenhj at 2018/5/11 纯粹技术债务,永远过滤金牌订单(假单)
        if not demand or demand.status in (
            DemandStatus.DRAFT.value, DemandStatus.UNCHECKED.value,
            DemandStatus.INVALID.value
        ) or demand.for_gold:
            return Response(DEMAND_NOT_EXIST)

        token = request.cookies.get('opc_token')
        # 如果是工程商登录, 则参与状态改为该工程商对此项目的参与状态
        user = AuthToken.verify_auth_token(token) if token else None

        # 如果是派单中的项目, 则判断登录的用户是否是派单所达的客户
        # 未登录或者不是派单用户, 都返回项目不存在
        if demand.status in (
            DemandStatus.DISPATCHING.value, DemandStatus.MASTER_DISPATCHING.value
        ):
            if not user or not Partic.query.filter(
                Partic.demand_id == demand.id,
                Partic.supplier_id == user.id,
                Partic.demand_status.in_([
                    DemandStatus.DISPATCHING.value,
                    DemandStatus.MASTER_DISPATCHING.value
                ])
            ).first():
                return Response(DEMAND_NOT_EXIST)

        # 如果是铜牌一口价订单, 则判断登录且用户是否有效的铜牌用户
        if demand.status == DemandStatus.BRONZE_MEDAL_DISCOUNT.value:
            if not user or not user.bronze_medal_valid:
                return Response(DEMAND_NOT_EXIST)

        return Response(SUCCESS, {
            'info': generate_demand_info_json(demand, user)
        })


@api.resource('/marketing/demand/info')
class MarketingDemandResource(Resource):
    """
    create by ld_wu 2018-05-09
    拉新项目详情（不考虑是否有查询的权限）
    """
    def post(self):
        """
        created by chenhj at 2017/8/15

        """
        data, errors = demand_id_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        demand = Demand.get_by_id(data['id'])
        if not demand or demand.status in (
            DemandStatus.DRAFT.value, DemandStatus.UNCHECKED.value,
            DemandStatus.INVALID.value
        ):
            return Response(DEMAND_NOT_EXIST)

        token = request.cookies.get('opc_token')
        # 如果是工程商登录, 则参与状态改为该工程商对此项目的参与状态
        user = AuthToken.verify_auth_token(token) if token else None

        return Response(SUCCESS, {
            'info': generate_demand_info_json(demand, user)
        })


@api.resource('/Demand/addScan')
class DemandAddScanResource(Resource):
    """
    add by zhouhl 2017-09-06
    """
    def post(self):
        data, errors = demand_id_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        demand = Demand.get_by_id(data['id'])
        if not demand:
            return Response(DEMAND_NOT_EXIST)

        demand.scan_count += 1

        # add by zhouhl 2018-05-07
        # 记录用户访问次数
        token = request.cookies.get('opc_token')
        user = AuthToken.verify_auth_token(token) if token else None
        if user:
            UserVisitDemand.visit_counter(
                user.id, demand.id, UserVisitDemandChannel.WX.value
            )

        return Response()


@api.resource('/d/<d_id>-<u_id>')
class DemandJumpResource(Resource):
    """
    created by chenhj at 2017/8/22
    这个接口是用于跳转的, d_id为项目id的十六进制, u_id为用户的十六进制
    """
    def get(self, d_id, u_id):
        demand_id = int(d_id, 16)
        pattern = re.compile(r'^[0-9a-fA-F]+')
        match = pattern.search(u_id)
        if match:
            u_id = match.group()
        else:
            abort(404)
        user_id = int(u_id, 16)

        demand = Demand.get_by_id(demand_id)
        user = User.get_by_id(user_id)

        # 出错则跳转到工程商的404页面
        if not demand or not user:
            host = os.environ.get('sm_host')
            redirect_url = urllib.parse.urljoin(host, '404.html')
            return redirect(redirect_url)

        if demand.uid == user.id:
            # 发布者则跳到客户网站
            host = os.environ.get('m_host')
        else:
            # 否则跳转到工程商网站
            host = os.environ.get('sm_host')
        # 跳转到详情页
        redirect_url = urllib.parse.urljoin(
            host, '#DemandDetail?did={}'.format(demand_id)
        )
        if user.sms_marketing_obj:
            # 更新用户的进站次数（营销用户）
            UserMarketingInfoJuly.update_view_count(user_id)

        token = AuthToken.generate_auth_token(TOKEN_TIMEOUT, user)
        response = redirect(redirect_url)
        response.set_cookie('opc_token', token)
        return response


@api.resource('/invite/btn')
class InviteButtonCountResource(AuthResource):
    """
    create by ld_wu 2018-04-26
    拉新（抢单及关注按钮）点击次数记录
    """

    def post(self):
        info = UserMarketingInfoJuly.get_or_create(self.user.id)
        btn_type = request.form.get('btn_type')
        if btn_type:
            btn_type = int(btn_type)
        if info:
            if btn_type == BtnType.BID:
                info.bid_click_count += 1
            elif btn_type == BtnType.ATTEND:
                if info.attend_click_count == 0:
                    # 首次点击立即关注发送提醒客户关注短信
                    content = {
                        'mobile': self.user.mobile,
                        'content': '欢迎加入LED屏在线派单平台！快快在微信上关注“万屏汇”公众号开始抢单吧~'
                    }
                    current_app.multi_sms_producer.send(json.dumps([content]))
                info.attend_click_count += 1
        return Response()


@api.resource('/Demand/finishImg')
class DemandFinishImgResource(AuthResource):
    """
    add by zhouhl 2017-09-06
    上传项目完成图片，用于申报项目完成
    """
    def post(self):
        """
        add by zhouhl 2017-09-06
        """
        # 不是工程商则直接返回
        if self.user.type != UserType.ENGINEER.value:
            return Response(NOT_ENGINEER)

        data, errors = demand_finish_img_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        demand_id = data['demand_id']
        im = Image.open(BytesIO(base64.b64decode(data['img'])))
        path = os.path.join(os.path.dirname(
            os.path.abspath(__file__)), 'img/demand_finish_img')
        tmp_filename = str(demand_id) + '_' + str(self.user.id)
        filename = '{filename}.{format}'.format(
            filename=tmp_filename,
            format=im.format.lower()
        )
        im.save('{path}/{filename}'.format(path=path, filename=filename), im.format)
        new_demand_finish_img = DemandFinishImg.create(
            user_id=self.user.id,
            demand_id=demand_id,
            img='demand_finish_img/{filename}'.format(filename=filename)
        )
        return Response(
            SUCCESS,
            {
                'img': new_demand_finish_img.img_url
            }
        )


@api.resource('/Demand/getParticInfo')
class DemandParticInfoResource(Resource):
    """
    create by ld_wu 2017-10-30
    获取项目抢单信息
    """
    def post(self):

        data, errors = demand_id_in_schema.load(request.form)
        if errors:
            return Response(PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0]))

        demand_id = data['demand_id']

        demand = Demand.get_by_id(demand_id)
        if not demand:
            return Response(DEMAND_NOT_EXIST)

        partic_supplier_list = current_app.redis.get(
            PARTIC_CACHE_KEY.format(demand_id=demand_id, demand_status=demand.status)
        ) or list()

        # 查询铜牌一口价下竞价成功信息
        bronze_partic_info = {}
        bronze_success_partic = Partic.query.filter(
            Partic.demand_id == demand.id,
            Partic.status.in_([
                ParticStatus.SUCCEED.value,
                ParticStatus.TIMEOUT_NOT_CONTACT.value,
                ParticStatus.NOT_CONTACT.value,
                ParticStatus.BALANCE_NOT_ENOUGH.value
            ]),
            Partic.demand_status == DemandStatus.BRONZE_MEDAL_DISCOUNT.value
        ).first()
        if bronze_success_partic:
            bronze_partic_info.update({
                'id': bronze_success_partic.supplier_id,
                'id_': bronze_success_partic.supplier_id,
                'nickname': bronze_success_partic.owner.nickname,
                'hide_nickname': bronze_success_partic.hide_nickname,
                'mobile': '****' + bronze_success_partic.owner.mobile[-4:],
                'follow_type': bronze_success_partic.follow_type,
                'status': bronze_success_partic.status,
                'voucher_id': bronze_success_partic.voucher_id,
                'contact_state': bronze_success_partic.contact_state,
                'contact_seconds': bronze_success_partic.contact_seconds,
                'bid_win_at': bronze_success_partic.bid_win_at,
            })

        if not partic_supplier_list:
            partics = Partic.demand_partics(demand)

            for partic in partics:
                # 未来的报价不返回(系统插入的虚拟报价可能在当前时间之后, 并过滤掉铜牌一口价数据)
                if (
                    partic.offer_at - get_timestamp() <= 0
                    and partic.demand_status != DemandStatus.BRONZE_MEDAL_DISCOUNT.value
                ):
                    partic_supplier_list.append({
                        'id': partic.supplier_id,
                        'id_': partic.supplier_id,
                        'status': partic.status,
                        'nickname': partic.owner.nickname,
                        'hide_nickname': partic.hide_nickname,
                        'mobile': '****' + partic.owner.mobile[-4:],
                        'com': partic.owner.com,
                        'avatar': partic.owner.avatar_url,
                        'online': 0,
                        'partic_at': partic.created_at,
                        'offer_at': partic.offer_at,
                        'is_breach': partic.is_breach,
                        'breach_count': partic.owner.breach_count,
                        'contact_state': partic.contact_state,
                        'contact_seconds': partic.contact_seconds,
                        'bid_win_at': partic.bid_win_at,
                        'is_robot': partic.is_robot,
                        'offer': str(partic.offer),
                        'voucher_id': partic.voucher_id
                    })

            current_app.redis.set(
                PARTIC_CACHE_KEY.format(demand_id=demand.id, demand_status=demand.status),
                json.dumps(partic_supplier_list),
                ex=PARTIC_CACHE_TIMEOUT
            )
        else:
            logging.info('partic info get from cache: [demand_id]'.format(demand_id=demand_id))
            partic_supplier_list = json.loads(partic_supplier_list)

        # 是否有人爆灯
        has_max = False
        if demand.status == DemandStatus.ONGOING.value:
            has_max = (MAX_OFFER <= demand.max_partic_offer)

        token = request.cookies.get('opc_token')
        login_user = AuthToken.verify_auth_token(token)
        dispatch_winner = None
        if login_user and login_user.enterprise_info:
            if login_user.highest_level != EnterpriseLevel.LEVEL_6.value:
                # 非地方合作伙伴, 取同企业下中标人
                enterprise_cond = (Partic.enterprise_id == login_user.enterprise_info)
            else:
                # 地方合作伙伴, 取所有地方合作伙伴企业下中标人
                enterprise_cond = (Partic.enterprise_level == EnterpriseLevel.LEVEL_6.value)
            # 检查企业下或所有白金企业中是否有中标人
            winner_partic = Partic.query.filter(
                Partic.demand_id == demand.id,
                Partic.demand_status.in_([
                    DemandStatus.DISPATCHING.value,
                    DemandStatus.MASTER_DISPATCHING.value
                ]),
                enterprise_cond,
                Partic.status == ParticStatus.SUCCEED.value,
            ).first()
            if winner_partic:
                dispatch_winner = {
                    'id': winner_partic.owner.id,
                    'nickname': winner_partic.owner.nickname,
                    'mobile': '****' + winner_partic.owner.mobile[-4:],
                    'contact_state': winner_partic.contact_state,
                    'contact_seconds': winner_partic.contact_seconds,
                }

        return Response(
            SUCCESS,
            {
                'demand_status': demand.status,
                'has_max': has_max,
                'partic_supplier_list': partic_supplier_list,
                'bronze_partic_info': bronze_partic_info,
                'dispatch_winner': dispatch_winner
            }
        )


@api.resource('/enterprise/dispatch_demands')
class EnterpriseDispatchDemandsResource(AuthResource):
    """
    created by chenhj at 2018/8/8

    """
    def post(self):
        """
        created by chenhj at 2018/8/8

        """
        if self.user.type != UserType.ENGINEER.value:
            return Response(NOT_ENGINEER)

        if not self.user.enterprise_info:
            return Response(NOT_ENTERPRISE_USER)

        enterprise_id = self.user.enterprise_info

        data, errors = enterprise_dispatch_in_schema.load(request.form)
        if errors:
            return Response(
                PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0])
            )

        query_type = data['query_type']
        today = date.today()
        if query_type == EnterpriseDispatchQueryType.THIS_WEEK:
            start = today - timedelta(days=today.weekday())
            end = today + timedelta(days=1)
        elif query_type == EnterpriseDispatchQueryType.THIS_MONTH:
            start = date(today.year, today.month, 1)
            end = today + timedelta(days=1)
        elif query_type == EnterpriseDispatchQueryType.LAST_MONTH:
            last_month = today - timedelta(days=31)
            start = date(last_month.year, last_month.month, 1)
            end = date(last_month.year, today.month, 1)
        else:
            # 自定义
            if 'self_month' not in data:
                return Response(
                    PARAMS_ILLEGAL.new_format_msg('自定义月份不合法')
                )
            self_month = data['self_month']
            if self_month == 99:
                start = end = None
            else:
                start = date(today.year, self_month, 1)
                next_month = start + timedelta(days=31)
                end = date(today.year, next_month.month, 1)

        if start and end:
            start = start.strftime('%s')
            end = end.strftime('%s')
            cond = and_(
                Partic.enterprise_id == enterprise_id,
                Partic.created_at.between(start, end)
            )
        else:
            cond = and_(Partic.enterprise_id == enterprise_id)

        ent = Enterprise.get_by_id(enterprise_id)
        # 派单总量
        dispatch_demands_ids = Partic.query.filter(
            cond
        ).with_entities(
            Partic.demand_id.distinct()
        )
        dispatch_demands_cnt = dispatch_demands_ids.count()
        # 跟进总量
        dispatch_follow_cnt = Partic.query.filter(
            cond,
            Partic.follow_type.in_([FollowType.KEEP.value, FollowType.LOCKED.value])
        ).with_entities(
            Partic.demand_id.distinct()
        ).count()
        # 派单剩余容量
        left_dispatch_cnt = ent.leave_dispatch_cnt
        # 到期日期
        expired_date = ent.expired_date.strftime('%F')

        demands = Demand.query.filter(
            Demand.id.in_(dispatch_demands_ids)
        ).order_by(Demand.published_at.desc())

        sort_val = data.get('sort_value', 0)
        if sort_val:
            demands = demands.filter(
                Demand.published_at < sort_val
            )
        demands = demands.limit(20)

        demand_list = enterprise_dispatch_out_schema.dump(demands)[0]

        for each_demand in demand_list:
            # 是否退单
            each_demand['is_revert'] = False
            # 跟进人
            each_demand['follower'] = None
            # 当前抢单成功人数
            each_demand['success_bid_count'] = demand_bid_count(
                each_demand['id'],
                each_demand['published_count'],
                db.session
            )
            demand_partic = Partic.query.filter(
                Partic.demand_id == each_demand['id'],
                Partic.enterprise_id == enterprise_id
            ).order_by(
                Partic.status.desc()
            ).first()
            if demand_partic:
                if demand_partic.status == ParticStatus.SUCCEED.value:
                    each_demand['follower'] = demand_partic.owner.nickname
                # 若是退单的, 则更新is_revert值
                each_demand['is_revert'] = demand_partic.is_revert

        return Response(info_dict=dict(
            dispatch_demands_cnt=dispatch_demands_cnt,
            dispatch_follow_cnt=dispatch_follow_cnt,
            left_dispatch_cnt=left_dispatch_cnt,
            expired_date=expired_date,
            demand_list=demand_list
        ))


@api.resource('/enterprise/dispatch_demands/export')
class EnterpriseDispatchDemandsExportResource(AuthResource):
    """
    created by chenhj at 2018/8/13

    """
    def post(self):
        """
        created by chenhj at 2018/8/13

        """
        if self.user.type != UserType.ENGINEER.value:
            return Response(NOT_ENGINEER)

        if not self.user.enterprise_info:
            return Response(NOT_ENTERPRISE_USER)

        enterprise_id = self.user.enterprise_info

        data, errors = enterprise_dispatch_export_schema.load(request.form)
        if errors:
            return Response(
                PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0])
            )

        query_type = data['query_type']
        today = date.today()
        if query_type == EnterpriseDispatchQueryType.THIS_WEEK:
            start = today - timedelta(days=today.weekday())
            end = today + timedelta(days=1)
        elif query_type == EnterpriseDispatchQueryType.THIS_MONTH:
            start = date(today.year, today.month, 1)
            end = today + timedelta(days=1)
        elif query_type == EnterpriseDispatchQueryType.LAST_MONTH:
            last_month = today - timedelta(days=31)
            start = date(last_month.year, last_month.month, 1)
            end = date(last_month.year, today.month, 1)
        else:
            # 自定义
            if 'self_month' not in data:
                return Response(
                    PARAMS_ILLEGAL.new_format_msg('自定义月份不合法')
                )
            self_month = data['self_month']
            if self_month == 99:
                start = end = None
            else:
                start = date(today.year, self_month, 1)
                next_month = start + timedelta(days=31)
                end = date(today.year, next_month.month, 1)

        if start and end:
            start = start.strftime('%s')
            end = end.strftime('%s')
        current_app.common_producer.send(
            json.dumps(
                dict(
                    backend='demand_backend',
                    func='dispatch_demands_export',
                    kwargs=dict(
                        enterprise_id=enterprise_id,
                        start=start,
                        end=end,
                        email=data['email'],
                        nickname=self.user.nickname
                    )
                )
            )
        )
        return Response()
